<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="./js/d3.v3.min.js"></script>
	<style type="text/css">
		svg{border: 1px solid #333;}
	</style>
	<script type="text/javascript">
		window.onload=function(){
			//添加svg画布
			var svg=d3.select("body").append("svg")
						.attr("width",600)
						.attr("height",400)
			//定义距离
			var margin={left:30,right:30,top:30,bottom:30}
			var H=400-margin.top-margin.bottom;

			//准备数据
			var arr=[
				{realname:"八戒",weight:200},
				{realname:"唐僧",weight:140},
				{realname:"孙悟空",weight:90},
				{realname:"沙和尚",weight:210},
			]

			// d3.max(arr)
			var max=d3.max(arr,(item)=>{
				return item.weight;
			})

			//创建线性比例尺
			var yScale=d3.scale.linear()
						.domain([0,max])
						.range([0,H])

			//创建序数比例尺
			var xScale=d3.scale.ordinal()
						//["八戒", "唐僧", "孙悟空", "沙和尚"]]
						.domain(arr.map(item=>item.realname))
						.rangeRoundBands([0,600])

			//定义y坐标轴
			var yAxis=d3.svg.axis()
						.scale(yScale)
						.orient("left")
						.ticks(10)

			//定义x坐标轴
			var xAxis=d3.svg.axis()
						.scale(xScale)
						.orient("bottom")
						.ticks(4)

			//添加分组
			var group= svg.append("g")
				.attr("transform",`translate(${margin.left},${margin.top})`)

			//绘制矩形
			group.selectAll("rect").data(arr).enter()
					.append("rect")
					.attr("x",(item,index)=>{
						// return 70*index
						return xScale(item.realname)+10
					})
					.attr("y",(item,index)=>{
						return H-yScale(item.weight);
					})
					.attr("width",50)
					.attr("height",(item,index)=>{
						return yScale(item.weight);
					})
					.attr("fill","steelblue")
					.on("mouseover",function(){
						d3.select(this).attr("fill","yellowgreen")
					})
					.on("mouseout",function(){
						d3.select(this).attr("fill","steelblue")
					})

			//添加y坐标轴		
			group.append("g").call(yAxis)
				.attr("transform",`translate(10,0)`)

			//添加x坐标轴
			group.append("g").call(xAxis)
				.attr("class","xAxis")
				.attr("transform",`translate(10,${H})`)

			//微调文字的位置，向左移动50px
			group.selectAll(".xAxis text")
				.attr("dx",-50)





		}
	</script>
</head>
<body>

</body>
</html>